﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq.Expressions;
using Yz.Base;
using Yz.Core.Extensions;
using Yz.DB.EFCore.Dal;
using Yz.Model.Constants;
using Yz.Model.Entities;
using Yz.Model.Enums;
using Yz.Model.Views;

namespace Yz.Manage.Controllers
{
    public class NoticeController : BaseController
    {
        private readonly IDbAccess<Notice> _noticeDbAccess;
        public NoticeController(IDbAccess<Notice> noticeDbAccess)
        {
            _noticeDbAccess = noticeDbAccess;
        }

        /// <summary>
        /// 公告新闻管理
        /// </summary>
        /// <returns></returns>  
        [Authorize(Roles = UserRoleName.Manager)]
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取公告新闻
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="noticeType"></param>
        /// <param name="title"></param>
        /// <returns></returns> 
        [AllowAnonymous]
        [Authorize(Roles = UserRoleName.Manager)]
        public JsonResult GetNoticeListByPage(int pageSize, int pageIndex, NoticeType noticeType = NoticeType.None, string title = "", DateTime? beginDate = null, DateTime? endDate = null)
        {
            var page = new ParaPage { SkipNum = (pageIndex - 1) * pageSize, TakeNum = pageSize };
            var orders = new List<ParaOrder<Notice>>() {
                new ParaOrder<Notice> { Order = p =>  p.UpdateTime  , IsAsc = false }
            };
            int companyId = 0;
            if (User.Identity.IsAuthenticated)
            {
                companyId = base.CompanyId;
            }
            Expression<Func<Notice, bool>> where = p => p.CompanyId == companyId;
            if (noticeType != NoticeType.None)
            {
                where = where.And(c => c.NoticeType == noticeType);
            }
            if (!title.IsEmpty())
            {
                where = where.And(c => c.Title.Contains(title));
            }
            if (beginDate != null)
            {
                where = where.And(c => c.UpdateTime > beginDate);
            }
            if (endDate != null)
            {
                where = where.And(c => c.UpdateTime < endDate.Value.Date.AddDays(1));
            }
            var returnSTlist = _noticeDbAccess.GetListByPage<VmNotice>(where, page, orders, hasTotal: true);
            return Json(returnSTlist.ToVmPageList());
        }

        /// <summary>
        /// 编辑公告新闻
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [Route("Notice/Edit")]
        [Route("Notice/Edit/{Id:min(1)}")]
        [Authorize(Roles = UserRoleName.Manager)]
        public IActionResult Edit(int Id = 0)
        {
            VmNotice notice = new VmNotice();
            if (Id > 0)
            {
                notice = GetNotice(Id);
            }
            ViewBag.notice = notice.ToJsonStr();
            return View();
        }

        /// <summary>
        /// 获取一个公告新闻
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        private VmNotice GetNotice(int Id)
        {
            int companyId = base.CompanyId;
            var myTemp = _noticeDbAccess.GetModel<VmNotice>(c => c.Id == Id && c.CompanyId == companyId);
            return myTemp;
        }

        /// <summary>
        /// 保存公告新闻
        /// </summary>
        /// <param name="noticeModel">公告新闻</param>
        /// <returns></returns>
        [HttpPost]
        [Authorize(Roles = UserRoleName.Manager)]
        public JsonResult SaveNotice(Notice noticeModel)
        {
            string refMsg = "";
            bool Suc = false;
            DateTime dnow = DateTime.Now;
            ReturnCode rcode = ReturnCode.Fail;
            string tName = "";
            int companyId = base.CompanyId;
            switch (noticeModel.NoticeType)
            {
                case NoticeType.RecruitmentInfo:
                    tName = "招考信息";
                    break;
                case NoticeType.RecruitmentNews:
                    tName = "招考要闻";
                    break;
                case NoticeType.EducationalDynamics:
                    tName = "教育动态";
                    break;
                default:
                    tName = "系统公告";
                    break;
            }
            if (noticeModel.Id > 0)
            {
                rcode = _noticeDbAccess.Update(p =>
                p.SetProperty(q => q.Title, noticeModel.Title)
                .SetProperty(q => q.Content, noticeModel.Content)
                .SetProperty(q => q.NoticeType, noticeModel.NoticeType)
                .SetProperty(q => q.UpdateTime, dnow)
               , u => u.Id == noticeModel.Id && u.CompanyId == companyId,
                c => c.Title == noticeModel.Title && c.CompanyId == companyId && c.Id != noticeModel.Id);
                if (rcode == ReturnCode.NoExit)
                {
                    refMsg = $"修改的{tName}不存在！";
                }
            }
            else
            {
                noticeModel.UserName = base.UserName;
                int userId = UserId;
                noticeModel.UserId = userId;
                noticeModel.CompanyId = companyId;
                rcode = _noticeDbAccess.Add(noticeModel, c => c.CompanyId == companyId && c.Title == noticeModel.Title);
            }
            if (rcode == ReturnCode.Success)
            {
                Suc = true;
                refMsg = "保存成功";
            }
            else if (rcode == ReturnCode.Exit)
            {
                refMsg = $"{tName}已经存在";
            }
            var result = new VmReturn { Suc = Suc, Msg = refMsg };
            return Json(result);
        }

        /// <summary>
        /// 删除公告新闻
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize(Roles = UserRoleName.Manager)]
        public JsonResult DelNotice(int Id)
        {
            string refMsg = "";
            bool Suc = false;
            int userId = UserId;
            ReturnCode rcode = _noticeDbAccess.Delete(c => c.Id == Id && c.UserId == userId);
            if (rcode == ReturnCode.Success)
            {
                Suc = true;
                refMsg = "删除成功";
            }
            else
            {
                refMsg = "删除失败";
            }
            var result = new VmReturn { Suc = Suc, Msg = refMsg };
            return Json(result);
        }

        /// <summary>
        /// 公告详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [Route("Notice/Detail/{Id:min(1)}")]
        public IActionResult Detail(int Id)
        {
            VmNotice notice = GetNotice(Id);
            ViewBag.notice = notice.ToJsonStr();
            return View();
        }
    }
}